package com.healthcloud.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelUtils {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)
		try {
			List<String[]> list = getStandardData();
			System.out.println(list.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static final DecimalFormat df=new DecimalFormat("#");
	
	public static List<String[]> getData(InputStream input,Integer sheetIndex,Integer startRow,Integer maxCell)throws Exception{
		Workbook workbook = WorkbookFactory.create(input);
		Sheet sheet = workbook.getSheetAt(sheetIndex);
		int lastLowNum = sheet.getLastRowNum();
		Iterator rows = sheet.rowIterator();
		List<String[]> result = new ArrayList<String[]>();
		String[] item;
		while(rows.hasNext()){
			Row row = (Row)rows.next();
			if(row == null)	continue;
			int rownum = row.getRowNum();
			if(rownum<startRow){
				System.out.println(row.getCell(0).getStringCellValue());
				continue;
			}
			int cellLength = row.getLastCellNum();
			cellLength = (maxCell<cellLength?maxCell:cellLength);
			item = new String[maxCell];
			System.out.println("读取第 "+rownum+" 行...");
			for(int i=0; i<cellLength; i++){
				Cell cell = (Cell)row.getCell(i);
				if(cell == null) continue;
				if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC){
					item[i]=df.format(cell.getNumericCellValue())+"";	
				}else{
					item[i]=StringUtils.trim(cell.getStringCellValue());
				}
				
				System.out.print(" "+item[i]+" ");
			}
			for (int i=cellLength; i<maxCell; i++){
				item[i] = "" ;
			}
			System.out.println("");
			result.add(item);
		}
		return result;
	}
	
	public static List<String[]> getStandardData(){
		try {
			String p = "C:/Users/leno/Desktop/test.txt";
			FileInputStream finput = new FileInputStream(p);
			return getData(finput, 0, 2, 5);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ArrayList<String[]>();
	}
}
